#include <iostream>
#include <string>
#include <SDL.h>
#include <SDL_net.h>

using namespace std;

int main(int argc, char* argv[]){
	UDPsocket sd; //定义服务器socket
	UDPpacket* p; //定义数据包
	int quit;
	//初始化SDL_net
	if (SDLNet_Init() < 0)
	{
		cout << "SDLNet_Init:" << SDLNet_GetError() << endl;
		return -1;
	}
	//打开一个socket端口15366
	if (!(sd = SDLNet_UDP_Open(15366)))
	{
		cout << "SDLNet_UDP_Open:" << SDLNet_GetError() << endl;
		return -1;
	}
	//给数据包开辟空间
	if (!(p = SDLNet_AllocPacket(512)))
	{
		cout << "SDLNet_AllocPacket:" << SDLNet_GetError() << endl;
		return -1;
	}
	quit = 0;
	while (!quit)
	{
		if (SDLNet_UDP_Recv(sd, p))//接收数据
		{
			cout << "UDP Packet incoming" << endl;
			cout << "Chan: " << p->channel << endl;
			cout << "Data: " << p->data << endl;
			cout << "Len: " << p->len << endl;
			cout << "MaxLen: " << p->maxlen << endl;
			cout << "Status: " << p->status << endl;
			short port = SDLNet_Read16(&p->address.port);
			unsigned char* ptr = (unsigned char*)&(p->address.host);
			char buffer[20] = { 0 };
			sprintf_s(buffer, "%d.%d.%d.%d", *ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3));
			cout << "Address:" << buffer << ":" << port << endl;
			memset(p->data, 0, p->maxlen);//清空缓存区数据
		}
	}
    
	SDLNet_UDP_Close(sd);
	SDLNet_FreePacket(p);
	SDLNet_Quit();
	return 0;
}